﻿using Footy.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Footy.Controllers
{
    public class GlobalController : Controller
    {
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            ValidateUserLogin();
            base.OnAuthorization(filterContext);
        }

        private void ValidateUserLogin()
        {
            if (!(Session[Constants.Session_UserID] is int))
            {
                var cookie = Request.Cookies[Constants.Session_UserID];
                var strLocalId = cookie == null ? "" : cookie.Value;
                int id = 0;
                if (int.TryParse(strLocalId, out id) && id > 0)
                {
                    using (var context = FootyDB.CreateContext())
                    {
                        var user = context.Users.Where(u => u.ID == id).FirstOrDefault();
                        if (user != null)
                        {
                            Session[Constants.Session_UserID] = user.ID;
                            Session[Constants.Session_UserName] = user.Username;
                            Session[Constants.Session_TeamName] = user.TeamName;
                        }
                    }
                }
            }
        }
    }
}
